/**
 * FyLLGen - A Java based tool for collecting and distributing family data
 *
 * Copyright (C) 2007-2011 Christian Packenius
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.chris_soft.fyllgen.menu.navigate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;

import de.chris_soft.fyllgen.data.Family;
import de.chris_soft.fyllgen.data.Person;

/**
 * Go to the (next) person without children.
 * @author Christian Packenius, 20110201.
 */
public class GotoNextLeafPerson implements Listener {
  /**
   * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
   */
  public void handleEvent(Event event) {
    // Create a list of all persons. The current person will be at index zero.
    Person currentPerson = Family.instance.getCurrentPerson();
    Person[] persons = Family.instance.getPersonsArray();
    List<Person> personList = new ArrayList<Person>();
    personList.addAll(Arrays.asList(persons));
    while (personList.get(0) != currentPerson) {
      personList.add(personList.remove(0));
    }

    // Get next person without children.
    for (int i = 1; i < personList.size(); i++) {
      Person person = personList.get(i);
      Person[] children = person.getChildren();
      if (children == null || children.length == 0) {
        Family.instance.setCurrentPerson(person, 1);
        break;
      }
    }
  }
}
